#include <string>
#include <unordered_map>
#include <fstream>
#include <sstream>
using namespace std;
/*
 * @lc app=leetcode.cn id=166 lang=cpp
 *
 * [166] 分数到小数
 */

// @lc code=start
typedef long long ll;
class Solution {
public:
    string fractionToDecimal(int num, int de) {
        ll numerator = num, denominator = de;
        if (numerator % denominator == 0) return to_string(numerator / denominator);
        stringstream res; int last = -1;
        unordered_map<ll, int> used;
        int x = numerator / abs(numerator) * denominator / abs(denominator);
        res << numerator / denominator << '.'; 
        numerator = abs(numerator % denominator);
        int i = 0;
        while (numerator) {
            if (used.count(numerator)) {
                last = used[numerator]; break;
            }
            used.insert({numerator, i});
            int divisor = abs(numerator * 10 / denominator);
            res << abs(numerator * 10 / denominator);
            numerator = abs(numerator * 10 % denominator);
            i++;
        }
        if (last == -1) return res.str();
        string temp; res >> temp;
        string rtn; int m = -1;
        if (x < 0) rtn.push_back('-');
        for (int j = 0; j < temp.size(); j++) {
            if (temp[j] == '.') m = 0;
            rtn.push_back(temp[j]);
            if (m == last) rtn.push_back('(');
            if (m >= 0) m++;
        }
        rtn.push_back(')');
        return rtn;
    }
};
// @lc code=end

